package org.dragonnova.business.service.impl;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.dragonnova.business.cache.EhCacheBean;
import org.dragonnova.business.common.Constants;
import org.dragonnova.business.dao.UserDao;
import org.dragonnova.business.model.User;
import org.dragonnova.business.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Sets;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private EhCacheBean ehCache;

	@Override
	public User getUserByName(String userName) throws Exception {
		return userDao.findUserByName(userName);
	}

	@Override
	public void insertUser(User user) throws Exception {
		userDao.insertUser(user);
	}

	@Override
	public boolean updateUser(User user) throws Exception {
		return userDao.updateUser(user) > 0 ? true : false;
	}

	@Override
	public List<User> findUser(Integer id, String searchText) throws Exception {
		if (searchText != null) {
			searchText = "%" + searchText + "%";
		}
		return userDao.findUser(id, searchText);
	}

	@Override
	public boolean delUser(Integer id) throws Exception {
		int result = userDao.delUser(id);
		return result > 0 ? true : false;
	}

	@Override
	public boolean addUser(User user) throws Exception {
		int result = userDao.addUser(user);
		return result > 0;
	}

	@Override
	public Set<User> getLoginUsers() throws Exception {
		Set<User> users = Sets.newTreeSet(new Comparator<User>() {

			@Override
			public int compare(User o1, User o2) {
				int name = o1.getUsername().compareTo(o2.getUsername());
				if (name == 0)
					return 0;

				if (o1.getLogin_time() != null && o2.getLogin_time() != null) {
					return o1.getLogin_time().compareTo(o2.getLogin_time());
				} else {
					return name;
				}
			}

		});

		Map<String, Object> oldUsers = ehCache
				.iterator(Constants.USER_CACHE_NAME);
		for (Iterator<Entry<String, Object>> iter = oldUsers.entrySet()
				.iterator(); iter.hasNext();) {
			Entry<String, Object> userEntry = iter.next();
			User user = null;
			if ((user = (User) userEntry.getValue()) != null) {
				users.add(user);
			}
		}
		return users;
	}
}
